<template>
  <div class="creative_request_upload-body-edit" v-show="creativeRequestDetail != null && creativeRequestDetail.finishedCreativeList != null && creativeRequestDetail.finishedCreativeList.length > 0">
    <el-form ref="creativeRequestForm" :model="creativeRequestForm" label-width="150px"
             :rules="creativeRequestFormRules">
      <div>
        <!-- 成品素材 -->
        <el-row>
          <div class="product_Search">
            <el-form-item label="设计师 :">
              <el-select id="id-offer-componets-creativerequest-conmponents-request-edit-prod-product_Search"
                         size="mini" v-model="designers" filterable
                         multiple
                         clearable
                         placeholder="请选择">
                <el-option v-for="(item) in allUserList"
                           v-if="designerIdListWithCreative.length == 0 || designerIdListWithCreative.includes(item.id)"
                           :key="item.id" :value="item.id"
                           :label="item.realName">
                </el-option>
              </el-select>
            </el-form-item>
              <div style="width: 150px;text-align: left;line-height: 28px;margin-left: -400px;margin-top:5px">共{{getCreativeRequestDetailProdListTotal(creativeRequestDetail)}}个素材</div>


            <div style="margin-right: 3em" v-if="userRole.optimize">
              <el-button id="id-offer-componets-creativerequest-conmponents-request-edit-prod-doProdAudit"
                         class="dialog-close" size="mini" type="success" @click="doProdAudit('agree')">全部同意</el-button>
              <el-button id="id-offer-componets-creativerequest-conmponents-request-edit-prod-product_Search-two"
                         class="dialog-close" size="mini" type="danger" plain @click="doProdAudit('reject')">全部拒绝
              </el-button>
            </div>
          </div>
          <div v-for="(creativeRequestDetailProd,index) in showProdList()" :key="index"
               class="product_Body">
            <div class="prod-step">
              <el-steps direction="vertical">
                <el-step v-if="creativeRequestDetailProd.demandIsProd == 1">
                  <div slot="title" class="step-title">
                    <div>成品素材</div>
                    <div>上传时间 {{ creativeRequestDetailProd.date }}</div>
                    <div>设计师 {{getDesignerNameList(creativeRequestDetailProd.designerList)}}</div>
                    <div>制作用时 {{getMakeTimeText(creativeRequestDetailProd.makeTime)}}</div>
                    <div>共{{ creativeRequestDetailProd.creativeList.length }}个素材</div>
                  </div>
                  <div class="product_isUpload_content" slot="description" style="min-height: 240px">
                    <div class="product_isUpload">
                      <ul class="el-upload-list el-upload-list--picture-card" style="display: flex;flex-wrap: wrap">
                        <div v-for="(creative, i) in creativeRequestDetailProd.creativeList" :key="i"
                             class="product_border">
                          <li class="el-upload-list__item is-ready">
<!--                            <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                            <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>-->
                            <div style="display: flex;justify-content: center;align-items: center;width: 100%;height: 100%">
                              <img
                                v-if="getCreativeDetailInfo(creative).detailType === 'image'"
                                class="el-upload-list__item-thumbnail creative"
                                style="width: auto;height: auto;max-width: 100%;max-height: 100%"
                                :src="creative.creativeUrl"
                                alt=""
                                @click="detailProdCreative(creative,$event)" showdetail="true"
                              />
                              <video v-if="getCreativeDetailInfo(creative).detailType === 'video'"
                                     style="width: auto;height: auto;max-height: 100%;max-width: 100%"
                                     class="el-upload-list__item-thumbnail creative" :src="creative.creativeUrl"
                                     @click="detailCreative(creative,$event)"></video>
                            </div>

                            <span class="el-upload-list__item-actions" @click="detailProdCreative(creative,$event)"
                                  showdetail="true">
                          <span
                              v-if="(creativeRequestDetailIndex == 0 && userRole.designer && getAuditStatus() == 1 && creative.demandStatus == 1)"
                              class="deleteBtn" @click="deleteCreative(creative,'finishedCreativeList')">
                              <i class="el-icon-delete"></i>
                              </span>
                        </span>
                            <div style="position: relative; top: -150px;text-align: left; font-size: 8px;"
                                 v-if="creative.creativeUrl !== '-1' && creative.creativeUrl !== '-2'">
                              <div class="prod_index">{{ (i + 1) }}</div>
                            </div>
                            <div
                              style="position: relative; top: -150px;text-align: right; font-size: 20px;margin-top: -34px;"
                              v-if="creative.creativeUrl !== '-1' && creative.creativeUrl !== '-2'">
                          <span v-if="creative.demandStatus == 2" style="color: lawngreen; border:2px solid lawngreen;"><i
                            class="el-icon-success">同意</i></span>
                              <span v-if="creative.demandStatus == 3"
                                    style="color: orangered; border:2px solid orangered;"><i
                                class="el-icon-error">拒绝</i></span>
                              <span v-if="creative.demandStatus != 2 && creative.demandStatus != 3"
                                    style="color: yellow; border:2px solid yellow;"><i
                                class="el-icon-s-check">待审</i></span>
                            </div>
                          </li>
                          <div class="productCreativeTest" style="margin-top: -24px;">
                            <el-tooltip class="item" effect="dark" :content="creative.localFilename"
                                        placement="top-start">
                              <div>
                                本地名称: {{ creative.localFilename }}
                              </div>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" :content="creative.creator"
                                        placement="top-start">
                              <div>
                                上传人: {{ (creative.creator) ? creative.creator : userInfo.real_name }}
                              </div>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" :content="creative.shortId"
                                        placement="top-start">
                              <div>
                                短ID: {{ func.optimizeValue(creative.shortId, -1, '') }}
                              </div>
                            </el-tooltip>
                          </div>
                          <el-radio-group style="margin-bottom: 5px;padding-left: 5px;" size="mini"
                                          v-model="creative.demandStatus"
                                          v-if="userRole.optimize">
                            <el-radio :label="2"
                                      :disabled="!(userRole.optimize && (getAuditStatus() == 1) && (creative.status != 1 && creative.status != 2))"
                                      @change="setAuditTimeInPreviewDlg(creative)">同意
                            </el-radio>
                            <el-radio :label="3"
                                      :disabled="!(userRole.optimize && (getAuditStatus() == 1) && (creative.status != 1 && creative.status != 2))"
                                      @change="setAuditTimeInPreviewDlg(creative)">拒绝
                            </el-radio>
                          </el-radio-group>
                          <el-input id="id-offer-componets-creativerequest-conmponents-request-edit-prod-getAuditStatus"
                                    type="textarea" :row="2" v-if="creative.demandStatus == 3"
                                    v-model="creative.demandAuditComment"
                                    :readonly="!(userRole.optimize && (creativeRequestDetailIndex > 0 || getAuditStatus() == 1) && (creative.status != 1 && creative.status != 2))"></el-input>
                        </div>
                      </ul>
                    </div>
                  </div>
                </el-step>
                <el-step v-if="creativeRequestDetailProd.demandIsProd == 0">
                  <div slot="title" class="step-title" style="display: flex;color: black;font-size: 14px">
                    <div>制作中素材</div>
                    <div>上传时间 {{ creativeRequestDetailProd.date }}</div>
                    <div>设计师 {{getDesignerNameList(creativeRequestDetailProd.designerList)}}</div>
                    <div>制作用时 {{getMakeTimeText(creativeRequestDetailProd.makeTime)}}</div>
                    <div>共{{ creativeRequestDetailProd.creativeList.length }}个素材</div>
                  </div>

                  <div class="product_isUpload_content" slot="description">
                    <div class="product_isUpload">
                      <ul class="el-upload-list el-upload-list--picture-card" style="display: flex;flex-wrap: wrap">
                        <div v-for="(creative, i) in creativeRequestDetailProd.creativeList" :key="i"
                             class="product_border">
                          <li class="el-upload-list__item is-ready">
<!--                            <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                            <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>-->
                            <div style="display: flex;justify-content: center;align-items: center;width: 100%;height: 100%">
                              <img
                                v-if="getCreativeDetailInfo(creative).detailType === 'image'"
                                class="el-upload-list__item-thumbnail creative"
                                style="width: auto;height: auto;max-height: 100%;max-width: 100%"
                                :src="creative.creativeUrl"
                                alt=""
                                @click="detailCreative(creative,$event)" showdetail="true"
                              />
                              <video v-if="getCreativeDetailInfo(creative).detailType === 'video'"
                                     style="width: auto;height: auto;max-height: 100%;max-width: 100%"
                                     class="el-upload-list__item-thumbnail creative" :src="creative.creativeUrl"
                                     @click="detailCreative(creative,$event)"></video>
                            </div>

                            <div style="position: relative; top: -150px;text-align: left; font-size: 8px;"
                                 v-if="creative.creativeUrl !== '-1' && creative.creativeUrl !== '-2'">
                              <div class="prod_index">{{ (i + 1) }}
                              </div>
                            </div>
                          </li>
                          <div class="productCreativeTest" style="margin-top: -24px;">
                            <el-tooltip class="item" effect="dark" :content="creative.localFilename"
                                        placement="top-start">
                              <div>
                                本地名称: {{ creative.localFilename }}
                              </div>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" :content="creative.creator"
                                        placement="top-start">
                              <div>
                                上传人: {{ (creative.creator) ? creative.creator : userInfo.real_name }}
                              </div>
                            </el-tooltip>
                          </div>
                          <el-input type="textarea" :row="2" v-model="creative.demandAuditComment"
                                    :readonly="!(userRole.optimize && (creativeRequestDetailIndex > 0 || getAuditStatus() == 1))"></el-input>
                        </div>
                      </ul>
                    </div>
                  </div>
                </el-step>
              </el-steps>
            </div>
          </div>

        </el-row>
      </div>

      <!-- 素材详情-->
      <el-dialog :visible.sync="detailCreativeDialog" append-to-body top="0px;" :modal-append-to-body="false"
                 :close-on-click-modal="true"
                 :show-close="false" :before-close="closeDetailDialog" width="60%" class="creative-detail-list">
        <div style="text-align: center; width: 100%; height: 100%">
          <div slot="title" style="text-align: right">
            <el-button id="id-offer-componets-creativerequest-conmponents-request-edit-prod-closeDetailDialog"
                       class="dialog-close" size="mini" icon="el-icon-close" @click="closeDetailDialog"
                       circle></el-button>
          </div>
          <img :src="detailCreativeUrl" v-show="detailType === 'image'"/>
          <video v-show="detailType === 'video'" ref="video" :src="detailCreativeUrl"
                 autoplay="autoplay" controls="controls" class="creative_edit"></video>
        </div>
      </el-dialog>


      <el-dialog title="素材详细信息" :visible.sync="prodCreativePreviewDialog.visible" append-to-body top="0px;"
                 :close-on-click-modal="false" :before-close="closeProdCreativePreviewDialog" width="60%">
        <div style="text-align: center;">
            <span class="demonstration" v-if="prodCreativePreviewDialog.creative != null">
              <div style="font-size: x-large; text-align: center;" biggerRadio>
                序号：【{{ prodCreativePreviewDialog.currIndex }}】
                <el-radio
                  :disabled="!(userRole.optimize && (getAuditStatus() == 1) && (prodCreativePreviewDialog.creative.status != 1 && prodCreativePreviewDialog.creative.status != 2))"
                  v-model="prodCreativePreviewDialog.creative.demandStatus"
                  @change="setAuditTimeInPreviewDlg(prodCreativePreviewDialog.creative)" :label="2"
                  style="margin-right: 23px" size="medium"><span style="font-size: x-large; ">通过</span>
                </el-radio>
                <el-radio
                  :disabled="!(userRole.optimize && (getAuditStatus() == 1) && (prodCreativePreviewDialog.creative.status != 1 && prodCreativePreviewDialog.creative.status != 2))"
                  v-model="prodCreativePreviewDialog.creative.demandStatus"
                  @change="setAuditTimeInPreviewDlg(prodCreativePreviewDialog.creative)" :label="3"
                  size="medium"><span style="font-size: x-large;">拒绝</span>
                </el-radio>
              </div>
              <div v-if="prodCreativePreviewDialog.creative.demandStatus == 3">
                <el-row style="text-align: center;">
                  <el-col span="4"></el-col>
                  <el-col span="4" style="text-align: right;">
                    <span style="color: blue;">拒绝描述: </span>
                  </el-col>
                  <el-col span="10" style="text-align: left;">
                    <el-input id="id-offer-componets-creativerequest-conmponents-request-edit-prod-getAuditStatus"
                              type="textarea" :row="2" v-model="prodCreativePreviewDialog.creative.demandAuditComment"
                              :readonly="!(userRole.optimize && (getAuditStatus() == 1) && (prodCreativePreviewDialog.creative.status != 1 && prodCreativePreviewDialog.creative.status != 2))"></el-input>
                  </el-col>
                  <el-col span="4"></el-col>
                </el-row>
              </div>
            </span>
          <div>
            <el-carousel trigger="click" class="carousel" :autoplay="false" arrow="always" prodCarousel ref="carousel"
                         :initial-index="prodCreativePreviewDialog.initialIndex" :style="previewFrameStyle()"
                         indicator-position="none"
                         height="100%"
                         @change="handleProdCreativePreviewChange">
              <el-carousel-item v-for="creative in prodCreativePreviewDialog.creativeList" :name="creative.id"
                                :key="creative.id" :style="previewFrameStyle()">
                <img v-show="getCreativeDetailInfo(creative).detailType === 'image'"
                     :src="getCreativeDetailInfo(creative).detailCreativeUrl" :style="previewStyle()">
                <video v-show="getCreativeDetailInfo(creative).detailType === 'video' " ref="prodCreativeVideo"
                       :src="getCreativeDetailInfo(creative).detailCreativeUrl"
                       :style="previewStyle()"
                       controls="controls"></video>
              </el-carousel-item>
            </el-carousel>
          </div>
          <div style="text-align: center;">
            <span class="demonstration">
              <el-row>
                <el-col>
                    <span
                      style="float: left;margin-left: 200px;width:200px;text-align: left;">短ID:{{
                        (prodCreativePreviewDialog.creative == null) ? "未选择素材" : prodCreativePreviewDialog.creative.shortId
                      }}</span>
                    <span
                      style="float: left;width:400px;text-align: left;">设计者:{{
                        (prodCreativePreviewDialog.creative == null || prodCreativePreviewDialog.creative.designer == "") ? "暂无设计者" : getDesignerNameList(prodCreativePreviewDialog.creative.designer)
                      }}</span>
                    <span
                      style="float: left;width:300px;text-align: left;">媒体:{{
                        (prodCreativePreviewDialog.creative == null || prodCreativePreviewDialog.creative.platform == "") ? "暂无媒体" : prodCreativePreviewDialog.creative.platform
                      }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <span
                    style="float: left;margin-left: 200px">设计思路:{{
                      (prodCreativePreviewDialog.creative == null || prodCreativePreviewDialog.creative.thought == "") ? "暂无设计思路" : prodCreativePreviewDialog.creative.thought
                    }}</span>
                </el-col>
              </el-row>
            </span>
          </div>
        </div>
      </el-dialog>

    </el-form>
    <div id="downloadContent" style="display: none;"></div>
  </div>
</template>

<script>
  import creativeRequestAppend from "../creativeRequestAppend";
  import originCreativeAdd from "../originCreativeAdd";
  import {getOfferDesigner} from "@/api/offer/creativerequest";
  import {getCreativeRequestList, getRejectedList, submit, getDetail, getUserId} from "@/api/offer/creativerequest";
  import {getDetail as getOriginCreativeDetail} from "@/api/offer/origincreative";
  import {getDetail as getCreativeDetail} from "@/api/offer/creative";
  import {getAllUser} from "@/api/user"
  import Moment from "moment";
  import {mapGetters} from "vuex";
  import {createWebSocket} from "@/util/ws";
  import {findArray, findByProp} from "@/util/util";
  import func from "@/util/func";

  export default {
    name: "request-edit-prod",
    components: {
      creativeRequestAppend,
      originCreativeAdd,
    },
    props: {
      offerId: String,
      platform: Array,
      id: String,
      title: String,
      userRole: Object,
      creativeRequestData: Object,
      creativeRequestDetail: Object,
      creativeRequestDetailIndex: Number,
    },
    data() {
      //媒体
      let checkDesigners = (rule, value, callback) => {
        if (value === null || value.length === 0) {
          return callback(new Error("请选择设计师"));
        } else {
          callback();
        }
      };
      return {
        whetherAudit: '',
        func: func,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
          },
        },
        designers: [],
        creativeRequestForm: {
          designers: [],//设计师
          planTime: '',//制作日期
          actualTime: '',//实际完成时间
        },

        allUserList: [],
        designerIdListWithCreative: [],
        creativeRequestFormRules: {
          designers: [
            {
              required: true,
              validator: checkDesigners,
              trigger: "change",
            },
          ],
        },
        detailCreativeDialog: false, //素材详情
        detailType: {}, //素材详情弹窗-素材类型
        detailCreativeUrl: "", //素材详情弹窗-素材URL

        deletedFinishedIds: [],

        prodCreativePreviewDialog: {
          visible: false,
          initialIndex: 0,
          creativeList: [],
          creative: null,
          currIndex: 1,
          creativessss: {},
        },
      };
    },
    computed: {
      ...mapGetters(["permission", "userInfo"]),
      isDesignerManager() {
        return (this.userRole.admin || this.userInfo.user_id == this.creativeRequestData.creativeRequest.designerManager);
      },
      creativeRequestDetailProdList() {
        //显示层级：批次时间（但显示日期）=>状态
        let prodList = [];//日期=>成品
        let mapProdList = {};
        let timeMap = {};
        if (this.creativeRequestDetail != null) {
          this.creativeRequestDetail.finishedCreativeList.forEach((creative) => {
            if(creative.oldDemandStatus == undefined) {
              creative.oldDemandStatus = creative.demandStatus;
            }
            //前后10秒为一组，避免同一次提交时间延迟偏差
            let time = Moment(new Date(creative.createTime)).format('YYYY-MM-DD HH:mm:ss');
            for(let t=0;t<20;t++) {
              let checkTime = timeMap[Moment(new Date(creative.createTime)).subtract(10 - t,'seconds').format('YYYY-MM-DD HH:mm:ss')];
              if(checkTime) {
                time = checkTime;
                break;
              }
            }
            timeMap[time] = time;
            let bundleId = (creative.bundleId != null && creative.bundleId != -1)?creative.bundleId:'';
            let key = (bundleId == '')?(time + '|' + creative.demandIsProd):(bundleId + '|' + creative.demandIsProd);
            let theProd = mapProdList[key];
            if (!theProd) {
              theProd = {
                date: Moment(new Date(creative.createTime)).format('YYYY-MM-DD'),//仅用于显示
                bundleId: bundleId,
                bundleCreateTime: creative.createTime,
                makeTime: creative.makeTime,
                demandIsProd: creative.demandIsProd,//没有要求按这个排序，但总觉得不排序不可靠
                designerList: [],
                creativeList: [],
              };
              mapProdList[key] = theProd;
              prodList.push(theProd);
            }
            theProd.creativeList.push(creative);
            let designerList = (creative.designer || '').split(',');
            designerList.forEach((one)=>{
              if(!theProd.designerList.includes(one)) {
                theProd.designerList.push(one);
              }
            })
          });
        }
        prodList.sort((a, b) => {
          if(a.bundleCreateTime > b.bundleCreateTime) {
            return -1;
          }
          if(a.bundleCreateTime < b.bundleCreateTime) {
            return 1;
          }
          if(a.demandIsProd != b.demandIsProd) {
            if(a.demandIsProd == 1) {
              return -1;
            } else {
              return 1;
            }
          }
          return 0;
        });
        prodList.forEach(item=>{
          item.creativeList.sort((a,b)=>{
            if(a.oldDemandStatus != b.oldDemandStatus) {
              if(a.oldDemandStatus == 2) {
                return 1;
              }
              if(b.oldDemandStatus == 2) {
                return -1;
              }
              if(a.oldDemandStatus == 3) {
                return 1;
              }
              if(b.oldDemandStatus == 3) {
                return -1;
              }
              return 0;
            }
          })
        });
        return prodList;
      },
    },
    beforeDestroy() {
      let self = this;
      if (self.socket) {
        self.socket.close();
        self.socket = null;
      }
    },
    created() {
      getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
        this.allUserList = res.data.data
      });
      this.buildDesignerListWithCreative();
      this.creativeRequestDetail.prodItemActiveName = 'creatives';

      this.creativeRequestForm.designers = func.toList(this.creativeRequestData.creativeRequest.designers);
      this.creativeRequestForm.planTime = this.creativeRequestData.creativeRequest.planTime;
      this.creativeRequestForm.actualTime = this.creativeRequestData.creativeRequest.actualTime;

      this.creativeRequestDetail.finishedCreativeList.forEach((creative) => {
        creative.oldDemandStatus = creative.demandStatus;
        if (creative.demandIsProd == 1 && creative.demandStatus != 3) {
          creative.demandAuditComment = '';
        }
      });
    },
    mounted() {
      this.initSocket();
    },
    methods: {
    getCreativeRequestDetailProdListTotal(creativeRequestDetail) {
      // ############################
      // 同编辑页的creativeRequestDetailProdList，但同批次内按照(1、优先展示被拒素材>通过素材>待审素材2、被拒素材显示由客户拒绝还是由优化师拒绝)排序
      // ############################

      //显示层级：批次时间（但显示日期）=>状态
      let prodList = [];//日期=>成品
      let mapProdList = {};
      let timeMap = {};

      let selectedDesignerList = [];
      if (this.designers != null && this.designers.length > 0) {
        selectedDesignerList = this.designers;
      }

      if (creativeRequestDetail.finishedCreativeList != null) {
        creativeRequestDetail.finishedCreativeList.forEach((creative) => {
          if(selectedDesignerList.length > 0) {
            let selectedDesigner = false;
            if(creative.designer != null && creative.designer != '') {
              let creativeDesignerList = creative.designer.split(',');
              for(let d=0;d<creativeDesignerList.length;d++) {
                if(selectedDesignerList.includes(creativeDesignerList[d])) {
                  selectedDesigner = true;
                  break;
                }
              }
            }
            if(!selectedDesigner) {
              return;
            }
          }
          //前后10秒为一组，避免同一次提交时间延迟偏差
          let time = Moment(new Date(creative.createTime)).format('YYYY-MM-DD HH:mm:ss');
          for(let t=0;t<20;t++) {
            let checkTime = timeMap[Moment(new Date(creative.createTime)).subtract(10 - t,'seconds').format('YYYY-MM-DD HH:mm:ss')];
            if(checkTime) {
              time = checkTime;
              break;
            }
          }
          timeMap[time] = time;
          let bundleId = (creative.bundleId != null && creative.bundleId != -1)?creative.bundleId:'';
          let key = (bundleId == '')?(time + '|' + creative.demandIsProd):(bundleId + '|' + creative.demandIsProd);
          let theProd = mapProdList[key];
          if (!theProd) {
            theProd = {
              date: Moment(new Date(creative.createTime)).format('YYYY-MM-DD'),//仅用于显示
              bundleId: bundleId,
              bundleCreateTime: creative.createTime,
              makeTime: creative.makeTime,
              demandIsProd: creative.demandIsProd,//没有要求按这个排序，但总觉得不排序不可靠
              designerList: [],
              creativeList: [],
            };
            mapProdList[key] = theProd;
            prodList.push(theProd);
          }
          theProd.creativeList.push(creative);
          let designerList = (creative.designer || '').split(',');
          designerList.forEach((one)=>{
            if(!theProd.designerList.includes(one)) {
              theProd.designerList.push(one);
            }
          })
        });
      }
      prodList.sort((a, b) => {
        if(a.bundleCreateTime > b.bundleCreateTime) {
          return -1;
        }
        if(a.bundleCreateTime < b.bundleCreateTime) {
          return 1;
        }
        if(a.demandIsProd != b.demandIsProd) {
          if(a.demandIsProd == 1) {
            return -1;
          } else {
            return 1;
          }
        }
        return 0;
      });
      prodList.forEach(item=>{
        item.creativeList.sort((a,b)=>{
          let a_status = a.demandStatus;
          if(a.status == 3) {
            a_status = a.status;
          }
          let b_status = b.demandStatus;
          if(b.status == 3) {
            b_status = a.status;
          }

          if(a_status != b_status) {
            if(a_status == 3) {
              return -1;
            }
            if(b_status == 3) {
              return 1;
            }
            if(a_status == 2) {
              return -1;
            }
            if(b_status == 2) {
              return 1;
            }
          }
          return 0;
        })
      });
      let i=prodList.length;
      // let arr=prodList;
      let sum=0;
      for(let j=0;j<i;j++){

        sum=sum+prodList[j].creativeList.length

      }
      console.log('arr',sum)
      return sum;

    },
      buildDesignerListWithCreative() {
        let designerIdList = [];
        this.creativeRequestDetail.finishedCreativeList.forEach((creative) => {
          let idList = (creative.designer || '').split(',');
          idList.forEach(id=>{
            if(!designerIdList.includes(id)) {
              designerIdList.push(id);
            }
          })
        });
        this.designerIdListWithCreative = designerIdList;
      },
      showProdList() {
        let prodList = this.creativeRequestDetailProdList;
        if (this.designers.length > 0) {
          let rl = []
          prodList.map((item) => {
            let theList = {...item};
            let newCreativeList = [];
            let newDesignerList = [];
            theList.creativeList.forEach(creative=>{
              let designerList = (creative.designer || '').split(',');
              for(let d=0;d<designerList.length;d++) {
                if(this.designers.includes(designerList[d])) {
                  newCreativeList.push(creative);
                  designerList.forEach(designer=>{
                    if(!newDesignerList.includes(designer)) {
                      newDesignerList.push(designer);
                    }
                  });
                  break;
                }
              }
            });
            if(newCreativeList.length > 0) {
              theList.creativeList = newCreativeList;
              theList.designerList = newDesignerList;
              rl.push(theList);
            }
          });
          return rl
        } else {
          return prodList
        }
      },
      getMakeTimeText(makeTime) {
        if(makeTime != null && makeTime > 0) {
          let hour = Math.floor(makeTime / 3600);
          let minute = Math.floor(makeTime / 60) % 60;

          if(hour > 0 || minute > 0) {
            return ((hour > 0)?(hour + '小时'):'') + ((minute > 0)?(minute + '分钟'):'');
          }
        }
        return '0分钟';
      },
      initSocket() {
        let self = this;
        if (!self.socket) {
          self.socket = createWebSocket('/api/blade-system/wss', 'json');
          if (self.socket) self.socket.ontextmessage = (msg) => {
            let msgObj = JSON.parse(msg);
            //console.log("socket receive:" + msg)
            if (msgObj) {
              if (msgObj.messageName === 'tenantMessage' && msgObj.data.messageName === 'creativeChanged') {
                if (msgObj.data.creativeIds != null) {
                  let creativeIdList = msgObj.data.creativeIds.split(",");
                  if (self.creativeRequestDetail != null) {
                    let creativeRequestDetail = this.creativeRequestDetail;
                    if (creativeRequestDetail.finishedCreativeList != null) {
                      creativeRequestDetail.finishedCreativeList.forEach((creative) => {
                        if (creativeIdList.includes(creative.id) && (creative.thumbnailUrl == -1 || creative.thumbnailUrl == -2)) {
                          getCreativeDetail(creative.id).then((res) => {
                            creative.thumbnailUrl = res.data.data.thumbnailUrl;
                            creative.creativeUrl = res.data.data.creativeUrl;
                            creative.shortId = res.data.data.shortId;
                          })
                        }
                      })
                    }
                  }
                }
              }
              if (msgObj.messageName === 'tenantMessage' && msgObj.data.messageName === 'originCreativeChanged') {
                if (msgObj.data.originCreativeIds != null) {
                  let originCreativeIdList = msgObj.data.originCreativeIds.split(",");
                  if (self.creativeRequestDetail != null) {
                    let creativeRequestDetail = this.creativeRequestDetail;
                    if (creativeRequestDetail.originalCreativeList != null) {
                      creativeRequestDetail.originalCreativeList.forEach((originCreative) => {
                        if (originCreativeIdList.includes(originCreative.id) && (originCreative.thumbnailUrl == -1 || originCreative.thumbnailUrl == -2)) {
                          getOriginCreativeDetail(originCreative.id).then((res) => {
                            originCreative.thumbnailUrl = res.data.data.thumbnailUrl;
                            originCreative.link = res.data.data.link;
                          })
                        }
                      })
                    }
                  }
                }
              }
            }
          };
          if (self.socket) self.socket.onerror = () => {
            this.$message({
              type: 'warning',
              message: '您的网络目前不稳定，数据可能不能自动刷新！'
            });
          };
        }
      },
      previewStyle() {
        let height = ((window.innerHeight < 300) ? 300 : (window.innerHeight - 160));
        return {
          maxWidth: '100%',
          maxHeight: height + 'px'
        };
      },
      previewFrameStyle() {
        let height = ((window.innerHeight < 300) ? 300 : (window.innerHeight - 160)) + 60;
        return {
          width: '100%',
          height: height + 'px'
        };
      },
      getAuditStatus() {
        return this.creativeRequestData.creativeRequestDetailList[0].auditStatus;
      },
      getPassedDetail(creativeRequestDetail) {
        let detailHis = {
          editSeq: -1,
          content: '',
          appendFiles: '',
          appendFileList: []
        };
        if (creativeRequestDetail != null && creativeRequestDetail.creativeRequestDetailHisList != null && creativeRequestDetail.creativeRequestDetailHisList.length > 0) {
          creativeRequestDetail.creativeRequestDetailHisList.forEach((his) => {
            if (his.auditStatus == 1 && his.editSeq > detailHis.editSeq) {
              detailHis.editSeq = his.editSeq;
              detailHis.content = his.content;
              detailHis.appendFiles = his.appendFiles;
              if (his.appendFiles != null && his.appendFiles.startsWith('[')) {
                detailHis.appendFileList = JSON.parse(his.appendFiles);
              } else {
                detailHis.appendFileList = [];
              }
            }
          });
        }
        return detailHis;
      },
      getHisFileList(his) {
        let fileList = [];
        if (his != null && his.appendFiles != null && his.appendFiles.startsWith('[')) {
          let appendFileList = JSON.parse(his.appendFiles);
          appendFileList.forEach((appendFile) => {
            fileList.push({
              name: appendFile.filename,
              url: appendFile.fileUrl,
            })
          });
        }
        return fileList;
      },
      getDesignerNameList(designers) {
        if (designers == null || designers.length == 0) {
          return '';
        }
        let list = null;
        if (typeof (designers) == 'string') {
          list = func.toList(designers);
        } else {
          list = designers;
        }
        let nameList = [];
        list.forEach(id => {
          let name = findByProp(this.allUserList, id, 'id', 'realName');
          nameList.push(name);
        })
        return nameList.join(',');
      },
      //素材详情
      /*
        查看素材
       */
      detailCreative(row) {
        if (event == null || event.target.getAttribute('showdetail') != 'true') {
          return;
        }
        let creativeDetailInfo = this.getCreativeDetailInfo(row);
        if (!creativeDetailInfo) {
          return;
        }
        this.detailCreativeDialog = true;
        this.detailType = creativeDetailInfo.detailType;
        this.detailCreativeUrl = creativeDetailInfo.detailCreativeUrl;
      },
      deleteCreative(creative, prop) {
        this.$confirm('请确认是否要删除该成品素材, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let creativeIndex = findArray(this.creativeRequestDetail[prop], creative.id, 'id');
          if (creativeIndex != -1) {
            this.deletedFinishedIds.push(creative.id)
            this.creativeRequestDetail[prop].splice(creativeIndex, 1)
          }
        }).catch(() => {
          return
        });
      },
      /**
       * 判断素材类型
       */
      getCreativeDetailInfo(row) {
        let url = row.creativeUrl;
        if (!url) {
          url = row.link;
        }
        if (!url) {
          return null;
        }
        let div = url.indexOf('?');
        if (div != -1) {
          url = url.substring(0, div);
        }
        let type;
        let urlType = url.split(".")[url.split(".").length - 1];
        let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
        let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
        if (imgList.includes(urlType)) {
          type = "image";
        } else if (videoList.includes(urlType)) {
          type = "video";
        }
        return {detailType: type, detailCreativeUrl: url};
      },
      /**
       * 素材详情 关闭
       */
      closeDetailDialog() {
        this.detailCreativeDialog = false;
        this.$refs.video.pause();
      },
      /**
       * 表单验证
       */
      validateForm() {
        let flag = false;
        this.$refs.creativeRequestForm.validate((valid) => {
          if (valid) {
            flag = true;
          } else {
            flag = false;
          }
        });
        return flag;
      },
      doProdAudit(type) {
        this.agreeQuantity = []
        this.refuseQuantity = []
        this.actualQuantity = []
        let changed = false;
        this.creativeRequestDetail.finishedCreativeList.forEach((creative) => {
          let a = 0
          if (type === 'agree') {
            let index = 0
            this.agreeQuantity.push(index++)
          }
          if (type === 'reject') {
            let i = 0
            this.refuseQuantity.push(i++)
          }
          this.actualQuantity.push(a++)
          if (creative.demandIsProd == 1) {
            if (creative.status != 1 && creative.status != 2) {
              let oldDemandStatus = creative.demandStatus;
              if (type == 'agree') {
                creative.demandStatus = 2;
              } else if (type == 'reject') {
                creative.demandStatus = 3;
              } else if (type == 'reset') {
                creative.demandStatus = creative.oldDemandStatus;
              }
              if (oldDemandStatus != creative.demandStatus) {
                changed = true;
              }
            }
          }
        });
        if (changed) {
          this.creativeRequestDetail.auditTime = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        }
        this.whetherAudit = "1"
      this.creativeRequestData.creativeRequest.whetherAudit = this.whetherAudit
      },
      getFirstPlatform(val) {
        if (val == null || val.length == 0) {
          return '';
        } else if (typeof val == 'string') {
          return val.split(',')[0];
        } else {
          return val[0];
        }
      },
      appendProductCreatives(creatives, index) {
        this.creativeRequestDetail.uploadTime = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        let dataList = this.creativeRequestDetail.finishedCreativeList;
        this.creativeRequestDetail.finishedCreativeList = [...dataList, ...creatives]
      },
      detailProdCreative(creative, event) {
        if (event == null || event.target.getAttribute('showdetail') != 'true') {
          return;
        }
        let creativeList = [];
        this.creativeRequestDetailProdList.forEach((prodList) => {
          prodList.creativeList.forEach((c) => {
            if (c.demandIsProd == 1) {
              creativeList.push(c);
            }
          });
        });
        this.prodCreativePreviewDialog.creativeList = creativeList;
        this.prodCreativePreviewDialog.creative = creative;

        this.prodCreativePreviewDialog.visible = true
        let creativeIndex = creativeList.indexOf(creative);

        this.prodCreativePreviewDialog.initialIndex = creativeIndex;
        this.prodCreativePreviewDialog.currIndex = creativeIndex + 1;
        if (this.$refs.carousel) {
          this.$refs.carousel.setActiveItem(creativeIndex)
        }
      },
      closeProdCreativePreviewDialog() {
        this.prodCreativePreviewDialog.visible = false;
        if (this.getCreativeDetailInfo(this.prodCreativePreviewDialog.creativeList[this.prodCreativePreviewDialog.currIndex - 1]).detailType === 'video') {
          this.$refs.prodCreativeVideo[this.prodCreativePreviewDialog.currIndex - 1].pause();
        }
        this.prodCreativePreviewDialog.detailType = '';
        this.prodCreativePreviewDialog.detailCreativeUrl = ''
      },
      handleProdCreativePreviewChange(currIdx, oldCurrIdx) {
        if (this.getCreativeDetailInfo(this.prodCreativePreviewDialog.creativeList[oldCurrIdx]).detailType === 'video')
          this.$refs.prodCreativeVideo[oldCurrIdx].pause();
        this.prodCreativePreviewDialog.currIndex = currIdx + 1;
        this.prodCreativePreviewDialog.creative = this.prodCreativePreviewDialog.creativeList[currIdx];
      },
      setAuditTimeInPreviewDlg(creative) {
        for (let index = 0; index < this.creativeRequestData.creativeRequestDetailList.length; index++) {
          let isFound = false;
          for (let n = 0; n < this.creativeRequestData.creativeRequestDetailList[index].finishedCreativeList.length; n++) {
            if (this.creativeRequestData.creativeRequestDetailList[index].finishedCreativeList[n].id == creative.id) {
              isFound = true;
              break;
            }
          }
          if (isFound) {
            this.creativeRequestData.creativeRequestDetailList[index].auditTime = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
            break;
          }
        }
        this.whetherAudit = '1'
      this.creativeRequestData.creativeRequest.whetherAudit = this.whetherAudit

      },

      saveInput() {
        if (this.creativeRequestDetailIndex == 0) {
          this.creativeRequestData.creativeRequest.designers = this.creativeRequestForm.designers.join(',');
          this.creativeRequestData.creativeRequest.planTime = this.creativeRequestForm.planTime;
          this.creativeRequestData.creativeRequest.actualTime = this.creativeRequestForm.actualTime;
          this.creativeRequestData.creativeRequest.whetherAudit = this.whetherAudit
        }
      },
      checkInput() {
        let finalMessage = null;
        let self = this;
        if (self.userRole.optimize) {
          let unconfirmedCount = 0;
          self.creativeRequestDetail.finishedCreativeList.forEach((creative) => {
            if (creative.demandIsProd == 1) {
              if (creative.demandStatus != 2 && creative.demandStatus != 3) {
                unconfirmedCount++;
              }
            }
          });
          if (unconfirmedCount > 0) {
            return '请审核完成品素材再提交！';
          }
        }
        if (self.creativeRequestDetailIndex == 0) {
          self.$refs.creativeRequestForm.validate((valid) => {
            if(!valid) {
              finalMessage = "输入检查不通过";
            }
          });
        }
        return finalMessage;
      },
    },
  };
</script>

<style scoped lang="scss">
  .creative_request_upload-body {
    width: 80%;
    margin: 10px auto;
    -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
    box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
    border-radius: 20px;
    padding: 15px;
  }

  .creative_request_upload-body-edit {
    width: 98%;
    border-radius: 10px;
    color: #101010;
    font-size: 14px;
    text-align: center;
    padding-top: 2em;
    font-family: Roboto;
    margin: auto auto 2em auto;
    border: 1px solid #e8e8e8;
    background: white;
  }

  .refCreative {
    a {
      cursor: pointer;
    }
  }

  .request_creativeNum {
    /deep/ .el-input.is-disabled .el-input__inner {
      color: black;
    }
  }

  .creative_list {
    /deep/ .el-upload-list__item {
      text-align: center;
      vertical-align: middle;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /deep/ .el-upload-list--picture-card {
      display: flex;
      flex-wrap: wrap;
    }

    .creative {
      max-height: 100%;
      max-width: 100%;
      height: auto;
      width: auto;
      vertical-align: middle;
    }
  }

  .creative-detail-list {
    .dialog-close {
      margin-bottom: 20px;
      background-color: rgba(255, 255, 255, 0);
      color: white;
    }

    /deep/ .el-dialog {
      background: rgba(255, 255, 255, 0);
      -webkit-box-shadow: none;
      box-shadow: none;
    }

    /deep/ .el-dialog__header {
      padding: 0;
    }

    img {
      width: auto;
      height: auto;
      max-width: 80%;
      max-height: 80vh;
    }

    /deep/ video {
      width: auto;
      height: auto;
      max-width: 80%;
      max-height: 80vh;
    }
  }

  .product_Search {
    display: flex;
    justify-content: space-between;
  }

  .product_Body {
    width: 90%;
    margin: 1em auto auto auto;

    .product_UploadDate {
      color: #00a2ff;
      font-weight: 600;
      border-bottom: solid 2px #BDC3C7;
      padding-bottom: 3px;
      padding-left: 3em;
      text-align: left;
    }

    .product_isUpload {
      margin-top: 10px;
      display: flex;

      .product_isUpload_label {
        width: 100px;
      }

      .product_isUpload_content {
        flex: 1;

        display: flex;
        flex-wrap: wrap;
      }

      /deep/ .el-upload-list--picture-card .el-upload-list__item {
        overflow: inherit;
      }

      .product_border {
        width: 150px;
        height: 330px;
        margin-right: 10px;
        box-sizing: border-box;
        border: 1px solid rgba(232, 232, 232, 100);
        border-radius: 5px;

        .productCreativeTest {
          font-size: 14px;
          margin: 5px;

          div {
            width: 100%;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            line-height: 2em;
          }
        }
      }
    }
  }

  .checkRequestHistory {
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-end;
    line-height: 28px;
    padding-right: 3em;

    a {
      padding-right: 2em;
      cursor: pointer;
    }
  }

  .prod-step {
    width: 94%;
    margin: 0 auto;

    .step-title {
      display: flex;
      color: black;
      font-size: 14px;

      div {
        margin-right: 2em;
        color: #333;
      }
    }

    /deep/ .el-step__icon-inner {
      display: none;
    }

    /deep/ .el-step.is-vertical .el-step__line {
      top: 20px;
    }

    /deep/ .el-step__icon {
      width: 10px;
      height: 10px;
    }

    .prod_index {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      line-height: 24px;
      background-color: rgba(22, 132, 253, 100);
      color: rgba(255, 255, 255, 100);
      font-size: 14px;
      text-align: center;
      font-family: Roboto;
    }

  }
</style>
